import React,{useState,useEffect} from 'react'
import useList from '../hooks/ue-list'
import { useQuery, useMutation, useQueryClient } from 'react-query'
import { getTopics, postTopic } from '../api/cnode';

const Cnode = () => {
    const [tab,setTab] = useState('');
    const client = useQueryClient();
    const {data,loading,error} = useQuery(//使用react-query库
        ['getTopics',tab],
        ()=>getTopics(tab)//利用axios.js发请求,将次函数声明传给useQuery，以此来传参数tab
        //基础的传参方式
        //()=>fetch('https://cnodejs.org/api/v1/topics?tab='+tab).then(res=>res.json())
    );

    // const [list,loading,handleTab] = useList()//自定义hook

    //发布的函数
    const mutation = useMutation(
        postTopic,
        {
            onError(error){
                console.log(error)
            },
            onSuccess(data){
                client.invalidateQueries(['getTopics',tab],);
            }
        }
    )
    const post = ()=>{
        mutation.mutate({
            title:'吴邪今年47',
            tab:'dev',
            content:'发布一条内容',
            accesstoken:'349fa206-93e7-46e9-9fd4-896e30b7553e'
        })
    }

    if(loading){
        return <div>loading...</div>
    }

    return (
        
        <div style={{display:'flex'}}>
            <div>
                <div>
                    <button>全部</button>
                    <button onClick={()=>setTab('good')}>精华</button>
                    <button onClick={()=>setTab('share')}>分享</button>
                    <button onClick={()=>setTab('ask')}>问答</button>   
                    <button onClick={()=>setTab('dev')}>测试</button>   
                </div>
                {
                    data?.data.map(item=>(
                    <li key={item.id}>{item.title}</li>
                    ))
                }
            </div>
            <div>
                <button disabled={mutation.isLoading} onClick={post}>发布</button>
            </div>
        </div>
    )
}

export default Cnode